import { Form, Input, Select, Cascader, Upload, Button, Icon, Radio, Table } from 'antd';
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import EditableTable from './EditableTable';
import SkuTagGroup from './SkuTagGroup';
import styles from './index.less';

const { Option } = Select;
let id = 0;

@connect(({ category, goods }) => ({
  cateData: category.cateData,
  attrs: goods.attrs,
}))
class Step2 extends Component {
  // static defaultProps = {
  //   data: {},
  // };
  BasicColumns = [
    {
      title: '净含量',
      dataIndex: 'name_1',
    },
    {
      title: '口味',
      dataIndex: 'name_2',
    },
    {
      title: '市场价',
      dataIndex: 'market_price',
      width: '20%',
      editable: true,
    },
    {
      title: '销售价',
      dataIndex: 'sell_price',
      width: '20%',
      editable: true,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      width: '20%',
      editable: true,
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      attrTags: [], // 当前规格下的标签tag
      basicColumns: this.BasicColumns,
      dataSource: [{
        id: 9,
        attr_values: [
          {
            attr_id: 1,
            attr_name: "净含量",
            attr_value_id: 1,
            attr_value_name: "350ml"
          }, {
            attr_id: 2,
            attr_name: "口味",
            attr_value_id: 3,
            attr_value_name: "原味"
          },
        ],
        market_price: "13.00",
        sell_price: "13.00",
        stock: 100,
        attachments: [],
      },
        {
          id: 10,
          attr_values: [{
            attr_id: 1,
            attr_name: "净含量",
            attr_value_id: 1,
            attr_value_name: "350ml",
          },
            {
              attr_id: 2,
              attr_name: "口味",
              attr_value_id: 4,
              attr_value_name: "百香果",
            },
          ],
          market_price: "13.00",
          sell_price: "13.00",
          stock: 100,
          attachments: [],
        },
      ],
    };
  }

  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
  };

  remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('keys');
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  // 选中规格写入到表格column，value={key:1, label:"口味"}
  handleSpecChange = (value) => {
    const { basicColumns } = this.state;
    const { attrs } = this.props;
    console.log('选中的值', value);
    const column = {
      title: value.label,
      dataIndex: `name_${value.key}`,
    };
    // 过滤出当前select下的values给到组件SkuTagGroup->attrTags
    const attrValues = attrs.filter(item => item.id === value.key).pop().values;
    this.setState({
      attrTags: attrValues,
      basicColumns: basicColumns.unshift(column),
    });
    console.log('组合后的columns', this.state);
  };

  // 处理表格column列根据select选择动态增删
  handleColumnSource = () => {

  };

  render() {
    const { cateData, form, attrs } = this.props;
    const { basicColumns, dataSource, attrTags } = this.state;

    console.log('attrTags', attrTags);

    const { getFieldDecorator, getFieldValue, validateFields } = form;
    const formItemLayout = {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 21,
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 21, offset: 3 },
      },
    };

    getFieldDecorator('keys', { initialValue: [] });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <Form.Item
        {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? '规格设置' : ''}
        required={false}
        key={k}
      >
        {getFieldDecorator(`names[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [
            {
              required: true,
              whitespace: true,
              message: '请填写规格或删除此字段',
            },
          ],
        })(
          <Select
            showSearch
            labelInValue
            style={{ width: 200, marginRight: 8 }}
            placeholder="请选择或填写规格"
            optionFilterProp="children"
            onChange={this.handleSpecChange}
            // onFocus={onFocus}
            // onBlur={onBlur}
            // onSearch={onSearch}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {attrs && (
              attrs.map(o => <Option value={o.id} key={o.id}>{o.name}</Option>)
            )}
          </Select>,
        )}
        <Icon
          className={styles.dynamic_delete_button}
          type="minus-circle-o"
          onClick={() => this.remove(k)}
        />
        <SkuTagGroup data={attrTags} />
      </Form.Item>
    ));

    return (
      <Fragment>
        <Form layout="horizontal" className={styles.stepForm}>
          <Form.Item {...formItemLayout} label="商品规格">
            {getFieldDecorator('good_name', {
              initialValue: 'a',
            })(
              <Radio.Group buttonStyle="solid" style={{ width: '100%' }}>
                <Radio.Button value="a">统一规格</Radio.Button>
                <Radio.Button value="b">多规格</Radio.Button>
              </Radio.Group>,
            )}
          </Form.Item>
          {formItems}
          <Form.Item {...formItemLayoutWithOutLabel}>
            <Button type="dashed" onClick={this.add} style={{ width: '40%' }}>
              <Icon type="plus" /> 添加规格
            </Button>
          </Form.Item>
          <Form.Item {...formItemLayout} label="SKU设置">
            {getFieldDecorator('sku', {
              rules: [
                { required: true, message: '请设置sku' },
              ],
            })(
              <EditableTable columns={basicColumns} dataSource={dataSource} />,
            )}
          </Form.Item>
          <Form.Item
            wrapperCol={{
              xs: { span: 24, offset: 0 },
              sm: {
                span: formItemLayout.wrapperCol.span,
                offset: formItemLayout.labelCol.span,
              },
            }}
            label=""
          >
            <Button type="primary">
              保存
            </Button>
            <Button style={{ marginLeft: 10 }}>
              下一步
            </Button>
          </Form.Item>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create()(Step2);
